package com.yeskery.nut.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;

/**
 * 文件资源实现类
 * @author YESKERY
 * 2024/8/13
 */
public class FileResourceImpl implements FileResource {

    /** 文件对象 */
    private final File file;

    /**
     * 构建文件资源实现类
     * @param file 文件对象
     */
    public FileResourceImpl(File file) {
        this.file = file;
    }

    @Override
    public boolean exists() {
        return file.exists();
    }

    @Override
    public URI getURI() {
        return file.toURI();
    }

    @Override
    public URL getURL() {
        try {
            return getURI().toURL();
        } catch (MalformedURLException e) {
            throw new NutException("File URL Obtain Fail.", e);
        }
    }

    @Override
    public File getFile() {
        return file;
    }

    @Override
    public long lastModified() {
        return file.lastModified();
    }

    @Override
    public boolean isReadable() {
        return file.canRead();
    }

    @Override
    public boolean isOpen() {
        return file.canExecute();
    }

    @Override
    public boolean isFile() {
        return file.isFile();
    }

    @Override
    public InputStream getInputStream() {
        try {
            return Files.newInputStream(file.toPath());
        } catch (IOException e) {
            throw new NutException("File InputStream Obtain Fail.", e);
        }
    }

    @Override
    public String getName() {
        return file.getName();
    }

    @Override
    public Long length() {
        return file.length();
    }
}
